package cc.magicjson.mall.product.application.service;

import cc.magicjson.mall.product.application.command.CreateProductCommand;
import cc.magicjson.mall.product.domain.model.Product;
import cc.magicjson.mall.product.domain.repository.ProductRepository;
import org.springframework.context.ApplicationEventPublisher;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;

@Service
public class ProductApplicationService {
	private final ProductRepository productRepository;
	private final ApplicationEventPublisher eventPublisher;

	public ProductApplicationService(ProductRepository productRepository, ApplicationEventPublisher eventPublisher) {
		this.productRepository = productRepository;
		this.eventPublisher = eventPublisher;
	}

	@Transactional
	public String createProduct(CreateProductCommand command) {
		if (productRepository.findByName(command.name()) != null) {
			throw new IllegalArgumentException("Product name already exists");
		}

		Product product = new Product(
				command.name(),
				command.description(),
				command.price(),
				command.stockQuantity()
		);

		product = productRepository.save(product);

		product.getDomainEvents().forEach(eventPublisher::publishEvent);
		product.clearDomainEvents();

		return product.getId();
	}

	public BigDecimal getProductPrice(String productId) {
		Product product = productRepository.findById(productId)
				.orElseThrow(() -> new RuntimeException("Product not found"));
		return product.getPrice();
	}
	// Other methods...
}